package co.yixiang.rest;

import cn.hutool.core.util.StrUtil;
import co.yixiang.annotation.AnonymousAccess;
import co.yixiang.aop.log.Log;
import co.yixiang.domain.LocalStorage;
import co.yixiang.domain.QiniuContent;
import co.yixiang.service.LocalStorageService;
import co.yixiang.service.QiNiuService;
import co.yixiang.service.dto.LocalStorageDTO;
import co.yixiang.service.dto.LocalStorageQueryCriteria;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author hupeng
 * @date 2020-01-09
 */
@Api(tags = "上传统一管理")
@RestController
@SuppressWarnings("unchecked")
public class UploadController {

    @Value("${file.localUrl}")
    private String localUrl;

    private final LocalStorageService localStorageService;

    private final QiNiuService qiNiuService;

    public UploadController(LocalStorageService localStorageService,QiNiuService qiNiuService) {
        this.localStorageService = localStorageService;
        this.qiNiuService = qiNiuService;
    }


    @ApiOperation("文件批量上传")
    @PostMapping("/uploads")
    @AnonymousAccess
    public ResponseEntity<Object> uploadFile(@RequestParam(defaultValue = "") String name, @RequestParam("files")MultipartFile[]  files) {
        System.out.println(files.length);

        List<Map> list = new ArrayList<>();
        if(StrUtil.isNotEmpty(localUrl)){ //存在走本地
            for(MultipartFile file : files){
                LocalStorageDTO localStorageDTO = localStorageService.create("", file);
                String fileName = file.getOriginalFilename();
                String url = localUrl+"/file/"+localStorageDTO.getType()+"/"+localStorageDTO.getRealName();
                Map<String,Object> map = new HashMap<>(2);
                map.put("fileName",fileName);
                map.put("errno",0);
                map.put("link",url);
                list.add(map);
            }
        }else{//走七牛云
            for(MultipartFile file : files) {
                QiniuContent qiniuContent = qiNiuService.upload(file, qiNiuService.find());
                String fileName = file.getOriginalFilename();
                String url = qiniuContent.getUrl();
                Map<String,Object> map = new HashMap<>(2);
                map.put("fileName",fileName);
                map.put("errno",0);
                map.put("link",url);
                list.add(map);
            }
        }

        return new ResponseEntity(list,HttpStatus.CREATED);
    }


    @ApiOperation("上传文件")
    @AnonymousAccess
    @PostMapping("/api/upload")
    public ResponseEntity<Object> create(@RequestParam(defaultValue = "") String name, @RequestParam("file") MultipartFile file){
        String url = "";
        if(StrUtil.isNotEmpty(localUrl)){ //存在走本地
            LocalStorageDTO localStorageDTO = localStorageService.create(name, file);
            url = localUrl+"/file/"+localStorageDTO.getType()+"/"+localStorageDTO.getRealName();
        }else{//走七牛云
            QiniuContent qiniuContent = qiNiuService.upload(file,qiNiuService.find());
            url = qiniuContent.getUrl();
        }

        Map<String,Object> map = new HashMap<>(2);
        map.put("errno",0);
        map.put("link",url);
        map.put("name",file.getOriginalFilename());
        System.out.println(map);
        return ResponseEntity.ok(map);
    }


    @ApiOperation("uni文件批量上传uploadFile")
    @PostMapping("/uploadFile")
    @AnonymousAccess
    public ResponseEntity<Object> uploadFile(HttpServletRequest request, @RequestParam("file")MultipartFile [] files) {
        CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());


        commonsMultipartResolver.setDefaultEncoding("utf-8");
        List<Map> list = new ArrayList<>();
        if (commonsMultipartResolver.isMultipart(request)){
            MultipartHttpServletRequest mulReq = (MultipartHttpServletRequest) request;
            Map<String, MultipartFile> map = mulReq.getFileMap();

            // key为前端的name属性，value为上传的对象（MultipartFile）
            for (Map.Entry<String, MultipartFile> entry : map.entrySet()) {
                if(StrUtil.isNotEmpty(localUrl)){ //存在走本地
                        // 自己的保存文件逻辑
                        LocalStorageDTO localStorageDTO = localStorageService.create("", entry.getValue());
                        String fileName = entry.getValue().getOriginalFilename();
                        String url = localUrl+"/file/"+localStorageDTO.getType()+"/"+localStorageDTO.getRealName();
                        Map<String,Object> fmap = new HashMap<>(4);
                        fmap.put("fileName",fileName);
                        fmap.put("errno",0);
                        fmap.put("link",url);
                        list.add(fmap);
                }else{//走七牛云
                        QiniuContent qiniuContent = qiNiuService.upload(entry.getValue(), qiNiuService.find());
                        String fileName = entry.getValue().getOriginalFilename();
                        String url = qiniuContent.getUrl();
                        Map<String,Object> fmap = new HashMap<>(3);
                        fmap.put("fileName",fileName);
                        fmap.put("errno",0);
                        fmap.put("link",url);
                        list.add(fmap);

                }

            }
        }

        return new ResponseEntity(list,HttpStatus.CREATED);
    }

}